package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.rholder.retry.*;
import com.yupi.springbootinit.RabbitMQ.BiProducer;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.MyRetryListener;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.ChartManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.StringEnum;
import com.yupi.springbootinit.model.vo.AiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 图表生成接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {
    @Resource
    private MyRetryListener myRetryListener;

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private ChartManager chartManager;
    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiProducer biProducer;
    @PostMapping ("/sendToMq")

    public void sendmq(String message){

        biProducer.send(message);
    }

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);

        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newchartId = chart.getId();
        return ResultUtils.success(newchartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldchart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);


        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

//    /**
//     * 分页获取列表（仅管理员）
//     *
//     * @param chartQueryRequest
//     * @return
//     */
//    @PostMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Page<Chart>> listchartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
//        long current = chartQueryRequest.getCurrent();
//        long size = chartQueryRequest.getPageSize();
//        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
//                getQueryWrapper(chartQueryRequest));
//        return ResultUtils.success(chartPage);
//    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);

        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldchart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String chartName = chartQueryRequest.getChartName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.like(StringUtils.isNotBlank(chartName), "chartName", chartName);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 智能分析
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<AiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        //获取请求头中的参数
        String chartName = genChartByAiRequest.getChartName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);
        //校验请求频繁，ps：获取资格证
        //key: xx用户使用xx方法的次数 也可以xx用户使用所用方法的次数 也可以某个方法使用次数 ps：限流粒度
        redisLimiterManager.rateLimit("genChartByAi" + loginUser.getId());
        //校验数据
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR, "用户未登陆");
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "名字太长");
        //校验文件
        String filename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        long one_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > one_MB, ErrorCode.FORBIDDEN_ERROR, "文件过大");
        String suffix = FileUtil.getSuffix(filename);
        final List<String> voidSuffix = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!voidSuffix.contains(suffix), ErrorCode.FORBIDDEN_ERROR, "文件不支持");
        //压缩后的csv数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        //通过ai获取图表前端代码
        String message;
        if (StringUtils.isNotBlank(chartType))
            message = csvData + "图表类型:" + chartType + "\n" + StringEnum.aiEnd;
        else message = csvData + StringEnum.aiEnd;
        String[] genResult = new String[2];

        Callable<Boolean> callable = () -> {
            log.info("是的发送发送发发发完安抚瓦房爱我我发完饭爱我发完饭瓦房瓦房瓦房瓦房瓦房瓦房瓦房瓦房");
            //图表可视化代码
            genResult[0] = chartManager.doChat(message);
            //保存历史记录供获取分析数据结果
            Map<String, String> hisMap = new HashMap<>();
            hisMap.put("提问", message);
            hisMap.put("回答", genResult[0]);
            //分析结果
            genResult[1] = chartManager.doAnalys(goal, hisMap);
            if(StringUtils.isNotBlank(genResult[0])){
                return false;
            }else {
                return true;
            }
            //todo guava 此处重传判断可改为 生成的代码是否符合echarts v5 ， 不符合则重传(此种方式更能用的上重传)
        };

        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(result -> result.equals(true))
                .withWaitStrategy(WaitStrategies.incrementingWait(10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withRetryListener(myRetryListener)
                .build();
        try {
            retryer.call(callable);
            log.info("正在重试ing------------------------------------");
        } catch (ExecutionException | RetryException e) {
            log.info("重试失败");
            throw new RuntimeException(e);
        }

        //插入数据库
        //todo 分库分表 xx用户某个字段过大会影响整个表查询效率
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genResult[0]);
        chart.setGenResult(genResult[1]);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        //返回响应体
        AiResponse aiResponse = new AiResponse();
        aiResponse.setGenChart(genResult[0]);
        aiResponse.setGenResult(genResult[1]);
        aiResponse.setId(chart.getId());
        return ResultUtils.success(aiResponse);
    }

    @PostMapping("/genAsync")
    public BaseResponse<AiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        //获取请求头中的参数
        String chartName = genChartByAiRequest.getChartName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);
        //校验请求频繁，ps：获取资格证
        //key: xx用户使用xx方法的次数 也可以xx用户使用所用方法的次数 也可以某个方法使用次数 ps：限流粒度
        redisLimiterManager.rateLimit("genChartByAi" + loginUser.getId());
        //校验数据
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR, "用户未登陆");
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "名字太长");
        //校验文件
        String filename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        long one_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > one_MB, ErrorCode.FORBIDDEN_ERROR, "文件过大");
        String suffix = FileUtil.getSuffix(filename);
        final List<String> voidSuffix = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!voidSuffix.contains(suffix), ErrorCode.FORBIDDEN_ERROR, "文件不支持");
        //压缩后的csv数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        //通过ai获取图表前端代码
        String message;
        if (StringUtils.isNotBlank(chartType))
            message = csvData + "图表类型:" + chartType + "\n" + StringEnum.aiEnd;
        else message = csvData + StringEnum.aiEnd;

        //插入数据库
        //todo 分库分表 xx用户某个字段过大会影响整个表查询效率
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        CompletableFuture.runAsync(() -> {
            //校验提交的任务的状态
            Chart chartById = chartService.getById(chart.getId());
            if (chartById.getStatus().equals(StringEnum.running)) {
                handlerChartUpdateError(chartById.getId(), "请勿重复提交");
            }
            //提交任务后，将数据库中相应任务改成执行态
            chartById.setStatus(StringEnum.running);
            boolean updatedById = chartService.updateById(chartById);
            if (!updatedById) {
                handlerChartUpdateError(chartById.getId(), "更新任务为执行态失败");
            }
            //图表可视化代码
            String chartCode = chartManager.doChat(message);
            //保存历史记录供获取分析数据结果
            Map<String, String> hisMap = new HashMap<>();
            hisMap.put("提问", message);
            hisMap.put("回答", chartCode);
            //分析结果
            String analys = chartManager.doAnalys(goal, hisMap);
            chartById.setGenChart(chartCode);
            chartById.setGenResult(analys);
            chartById.setStatus(StringEnum.succeed);
            boolean succeedResult = chartService.updateById(chartById);
            if (!succeedResult)
                handlerChartUpdateError(chartById.getId(), "更新任务为成功态失败");
        }, threadPoolExecutor);


        //返回响应体
        AiResponse aiResponse = new AiResponse();
        aiResponse.setId(chart.getId());
        return ResultUtils.success(aiResponse);
    }



    @PostMapping("/genAsyncMq")
    public BaseResponse<AiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        //获取请求头中的参数
        String chartName = genChartByAiRequest.getChartName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);
        //校验请求频繁，ps：获取资格证
        //key: xx用户使用xx方法的次数 也可以xx用户使用所用方法的次数 也可以某个方法使用次数 ps：限流粒度
        redisLimiterManager.rateLimit("genChartByAi" + loginUser.getId());
        //校验数据
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR, "用户未登陆");
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "名字太长");
        //校验文件
        String filename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        long one_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > one_MB, ErrorCode.FORBIDDEN_ERROR, "文件过大");
        String suffix = FileUtil.getSuffix(filename);
        final List<String> voidSuffix = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!voidSuffix.contains(suffix), ErrorCode.FORBIDDEN_ERROR, "文件不支持");
        //压缩后的csv数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        //通过ai获取图表前端代码
        String message;
        if (StringUtils.isNotBlank(chartType))
            message = csvData + "图表类型:" + chartType + "\n" + StringEnum.aiEnd;
        else message = csvData + StringEnum.aiEnd;

        //插入数据库
        //todo 分库分表 xx用户某个字段过大会影响整个表查询效率
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);

        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        biProducer.send(String.valueOf(chart.getId()));

        //返回响应体
        AiResponse aiResponse = new AiResponse();
        aiResponse.setId(chart.getId());
        return ResultUtils.success(aiResponse);
    }
    private void handlerChartUpdateError(long chartId, String errorMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setExeMessage(errorMessage);
    }
}
